package com.fivefu.core.config;

import com.fivefu.core.constants.DataSourceConstants;
import com.zaxxer.hikari.HikariDataSource;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.annotation.Order;

/**
 * @Author zhf
 * @Description
 * @Date 2021/3/4
 */
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
@Configuration
@MapperScan(basePackages = "com.fivefu.core.mapper")
@Order(5)
public class DynamicDataSourceConfig {

    private static  String jdbcUrl;

    private static String username;
    private static String password;

    private static String driver;

    @Bean(DataSourceConstants.DS_KEY_MASTER)
    public static DataSource masterDataSource() {
        //测试用Hikari
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setPoolName("hikari_master");
        hikariDataSource.setJdbcUrl(jdbcUrl);
        hikariDataSource.setUsername(username);
        hikariDataSource.setPassword(password);
        hikariDataSource.setDriverClassName(driver);
        return  hikariDataSource;
        //return DataSourceBuilder.create().url(jdbcUrl).username(username).password(password).driverClassName(driver).build();
    }

    @Bean
    @Primary
    public DataSource dynamicDataSource() {
        Map<Object, Object> datasourceMap = new HashMap<>(1);
        datasourceMap.put(DataSourceConstants.DS_KEY_MASTER, masterDataSource());
        return new FFDynamicDS(masterDataSource(), datasourceMap);
    }

   @Value("${spring.datasource.master.jdbc-url}")
    public  void setJdbcUrl(String jdbcUrl) {
        DynamicDataSourceConfig.jdbcUrl = jdbcUrl;
    }
    @Value("${spring.datasource.master.username}")
    public  void setUsername(String username) {
        DynamicDataSourceConfig.username = username;
    }
    @Value("${spring.datasource.master.password}")
    public  void setPassword(String password) {
        DynamicDataSourceConfig.password = password;
    }
    @Value("${spring.datasource.master.driver-class-name}")
    public  void setDriver(String driver) {
        DynamicDataSourceConfig.driver = driver;
    }
}
